package com.zxl.yjb.activity.payfee;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yjb.app.wxapi.WXPayEntryActivity;
import com.zxl.yjb.GlideApp;
import com.zxl.yjb.R;
import com.zxl.yjb.adapter.OrderListAdapter;
import com.zxl.yjb.app.MyApplication;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.CouponBean;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.bean.OrderBindBean;
import com.zxl.yjb.bean.WXOrderBean;
import com.zxl.yjb.bean.ZFBOrderBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.payfee.AuthResult;
import com.zxl.yjb.payfee.PayResult;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
 * 介绍 支付页面，为了省事，都使用微信支付的回调页面，记住，
 * “WXPayEntryActivity”绝对不能重命名或移动位置，否则微信支付回调失败
 * 作者 ssy
 * 时间 2017/8/7
 * 邮箱 1161209667@qq.com
 */
public class PayFeeActivity extends BaseActivity {

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    @BindView(R.id.iv_wx_pay)
    ImageView ivWxPay;
    @BindView(R.id.ll_wx_pay)
    LinearLayout llWxPay;
    @BindView(R.id.iv_zfb_pay)
    ImageView ivZfbPay;
    @BindView(R.id.ll_zfb_pay)
    LinearLayout llZfbPay;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_pay_fee)
    TextView tvPayFee;
    @BindView(R.id.tv_real_amount)
    TextView tv_real_amount;
    @BindView(R.id.rv_comment_list)
    RecyclerView rvCommentList;
    @BindView(R.id.et_amount)
    EditText etAmount;

    private String targetId;//
    private LoginSucessBean userInfo;
    private int payMethod = 1; // 1 支付宝 ；2 微信
    //微信API
    private IWXAPI api;
    private OrderListAdapter orderListAdapter;
    private String order_sn = "";
    private LinearLayoutManager layoutManager;

    /**总余额*/
    private String order_amount = "";
    /**折扣金额*/
    private String dec_per_order = "";
    /**折扣标准*/
    private String action_order_low_throughout = "";

    private String payment = "0";//原价
    private String payment_cal = "0";//折扣之后的价格
    private DecimalFormat dFormat;


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    Intent intent = new Intent(PayFeeActivity.this, WXPayEntryActivity.class);
                    //为了省事，使用微信支付的回调页面，记住，“WXPayEntryActivity”绝对不能重命名或移动位置
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(PayFeeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        intent.putExtra("payResult", "success");
                        startActivity(intent);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        Toast.makeText(PayFeeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        intent.putExtra("payResult", "fail");
                        startActivity(intent);
                        finish();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(PayFeeActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(PayFeeActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
    private String order_id;


    @Override
    protected void initView() {
        etAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                String temp = s.toString();
                if (TextUtils.isEmpty(temp))
                {
                    tv_real_amount.setText("");
                    return;
                }
                if(Double.parseDouble(temp) == 0)
                {
                    tv_real_amount.setText("");
                }
                int posDot = temp.indexOf(".");
                if (posDot > 0)
                {
                    if (posDot == 0)
                        s.delete(posDot, posDot);
                    if (temp.length() - posDot - 1 > 1)
                    {
                        s.delete(posDot + 2, posDot + 3);
                    }
                }

                String editpayment = s.toString();
                /*if (TextUtils.isEmpty(editpayment)||Double.parseDouble(editpayment) == 0)
                {
                    tv_real_amount.setText("");
                    return;
                }*/
                payment = editpayment;
                if (!TextUtils.isEmpty(order_amount)
                        &&!TextUtils.isEmpty(dec_per_order)
                        &&!TextUtils.isEmpty(action_order_low_throughout))
                {
                    if (Double.parseDouble(order_amount)>Double.parseDouble(dec_per_order)
                            &&Double.parseDouble(editpayment)>=Double.parseDouble(action_order_low_throughout))
                    {

                        double pay = Double.parseDouble(editpayment)-Double.parseDouble(dec_per_order);
                        if (pay<=0)
                        {
                            payment_cal = "0";
                        }
                        else
                        {
                            payment_cal = dFormat.format(pay)+"";
                        }
                        tv_real_amount.setText("已用优惠券，实付"+payment_cal+"元");

                    }
                    else
                    {
                        payment_cal = editpayment;
                    }
                }
                else
                {
                    payment_cal = editpayment;
                }

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_fee);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        //        orderInfo = getIntent().getStringExtra("orderInfo");
        targetId = getIntent().getStringExtra("targetId");
        userInfo = (LoginSucessBean) SaveBeanUtil.getBean(this, "vipInfo");
        //初始化微信支付api
        api = WXAPIFactory.createWXAPI(this, MyApplication.WXAPPID);
        api.registerApp(MyApplication.WXAPPID);
        dFormat = new DecimalFormat("0.00");
        initView();
        initAdapter();
        getOrderListForUser();
        getVoucherList();
    }

    private void initAdapter() {
        //创建布局管理
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvCommentList.setLayoutManager(layoutManager);
        //创建适配器
        orderListAdapter = new OrderListAdapter(R.layout.item_order_selecte);
        //给RecyclerView设置适配器
        rvCommentList.setAdapter(orderListAdapter);
        orderListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                order_sn = (String) view.getTag();
                orderListAdapter.setRefrenshItem(position);
                ImageView imageView = view.findViewById(R.id.iv_selected);
                OrderBindBean itemOrderBind = (OrderBindBean) adapter.getItem(position);
                order_sn = itemOrderBind.getOrder_sn();
                order_id = itemOrderBind.getOrder_id();
                GlideApp.with(getApplication()).load(R.mipmap.login_f_pressed).into(imageView);
//                GlideApp.with(getApplication()).load(R.mipmap.login_f_pressed).error(R.mipmap.login_f_pressed).dontAnimate().into(viewHolder.ivHeader);

            }
        });
    }


    private void getVoucherList() {

        DataManager dataManager = new DataManager();
        ObserverOnNextListener<CouponBean> listener = new ObserverOnNextListener<CouponBean>() {
            @Override
            public void onNext(CouponBean couponBean) {
                order_amount = couponBean.getVoucher().getOrder_amount();
                dec_per_order = couponBean.getVoucher_rule().getDec_per_order()+"";
                action_order_low_throughout = couponBean.getVoucher_rule().getAction_order_low_throughout()+"";
            }
        };
        dataManager.voucherList(new ProgressObserver<CouponBean>(listener, this));
    }


    private void Pay() {
        if (TextUtils.isEmpty(order_sn)) {
            ToastUtils.show(getApplicationContext(), "请选择订单！");
            return;
        }
        String money = etAmount.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            ToastUtils.show(getApplicationContext(), "请输入金额！");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("paytype", payMethod == 1 ? "alipay" : "wx");
        map.put("order_id", order_id);
        map.put("order_sn", order_sn);
        map.put("money_amount", payment);//原价
        map.put("money_amount_cal", payment_cal);//折扣之后的价格
        map.put("response_id", targetId);
        map.put("subject", "一键帮接单");

        if (payMethod == 1) {
            alipay(map);//支付包
        } else if (payMethod == 2) {
            wxPay(map);//微信
        }
    }

    @OnClick({R.id.ll_wx_pay, R.id.ll_zfb_pay, R.id.tv_cancel, R.id.tv_pay_fee})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_wx_pay:
                ivWxPay.setImageResource(R.mipmap.login_f_pressed);
                ivZfbPay.setImageResource(R.mipmap.login_f_normal);
                payMethod = 2;
                break;
            case R.id.ll_zfb_pay:
                ivWxPay.setImageResource(R.mipmap.login_f_normal);
                ivZfbPay.setImageResource(R.mipmap.login_f_pressed);
                payMethod = 1;

                break;
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_pay_fee:
                Pay();
                break;
        }
    }


    private void getOrderListForUser() {
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("user id", userInfo.getUid() + "");
        map.put("chatuid", targetId);
        map.put("page", "1");
        map.put("count", "100");
        ObserverOnNextListener<List<OrderBindBean>> listener = new ObserverOnNextListener<List<OrderBindBean>>() {
            @Override
            public void onNext(List<OrderBindBean> orderBindBeans) {
                orderListAdapter.addData(orderBindBeans);
                if (orderBindBeans.size() == 1)
                {
                    orderListAdapter.setRefrenshItem(1);
                    OrderBindBean itemOrderBind = orderBindBeans.get(0);
                    itemOrderBind.setSelect(true);
                    orderListAdapter.notifyDataSetChanged();
                    order_sn = itemOrderBind.getOrder_sn();
                    order_id = itemOrderBind.getOrder_id();
                }
            }
        };
        dataManager.getOrderListForUser(new ProgressObserver<List<OrderBindBean>>(listener, this), map);
    }

    //开始调用支付宝支付
    public void alipay(Map<String, String> map) {
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<ZFBOrderBean> listener = new ObserverOnNextListener<ZFBOrderBean>() {
            @Override
            public void onNext(ZFBOrderBean orderBean) {
                final String orderInfo = orderBean.getCredential().getAlipay().getOrderInfo();
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayFeeActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        };
        dataManager.payZFB(new ProgressObserver<ZFBOrderBean>(listener, this) {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.show(getApplicationContext(), "操作失败");
            }
        }, map);


    }

    /**
     * 微信支付
     *
     * @param map
     */
    public void wxPay(Map<String, String> map) {
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<WXOrderBean> listener = new ObserverOnNextListener<WXOrderBean>() {
            @Override
            public void onNext(WXOrderBean wxOrderBean) {
                WXOrderBean.CredentialBean.WxBean wxPayBean = wxOrderBean.getCredential().getWx();
                PayReq req = new PayReq();
                req.appId = MyApplication.WXAPPID;//AppID
                req.partnerId = wxPayBean.getPartnerId();//商户号--
                req.prepayId = wxPayBean.getPrepayId();//预支付交易会话ID--
                req.nonceStr = wxPayBean.getNonceStr();//随机字符串--
                req.timeStamp = wxPayBean.getTimeStamp() + "";//时间戳--
                req.packageValue = wxPayBean.getPackageValue();//扩展字段
                req.sign = wxPayBean.getSign();//签名--
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                api.sendReq(req);
            }
        };
        dataManager.payWX(new ProgressObserver<WXOrderBean>(listener, this) {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.show(getApplicationContext(), "操作失败");
            }
        }, map);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {
        if ("payfinish".equals(messageEvent.getMessage())) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
